{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   },
   "source": [
    ".. _nb_binary:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Binary Variable Problem\n",
    "\n",
    "Mostly, *pymoo* was made for continuous problem, but of course other variable types can be used as well. The genetic algorithm is a very modular class and by modifying the sampling, crossover and mutation (in some cases also repair), different kind of variable types can be used (also more complicated ones such as tree, graph, ...)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the following the classical knapsack problem is considered. A single-objective genetic algorithm with a random initial population, half uniform binary crossover and a bitflip mutation is initialized."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Best solution found: [1 0 0 0 1 0 1 1 0 0 1 0 0 0 0 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0]\n",
      "Function value: [-686]\n",
      "Constraint violation: [0.]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "from pymoo.algorithms.so_genetic_algorithm import GA\n",
    "from pymoo.factory import get_crossover, get_mutation, get_sampling\n",
    "from pymoo.optimize import minimize\n",
    "from pymoo.problems.single.knapsack import create_random_knapsack_problem\n",
    "\n",
    "problem = create_random_knapsack_problem(30)\n",
    "\n",
    "algorithm = GA(\n",
    "    pop_size=200,\n",
    "    sampling=get_sampling(\"bin_random\"),\n",
    "    crossover=get_crossover(\"bin_hux\"),\n",
    "    mutation=get_mutation(\"bin_bitflip\"),\n",
    "    eliminate_duplicates=True)\n",
    "\n",
    "res = minimize(problem,\n",
    "               algorithm,\n",
    "               ('n_gen', 100),\n",
    "               verbose=False)\n",
    "\n",
    "print(\"Best solution found: %s\" % res.X.astype(np.int))\n",
    "print(\"Function value: %s\" % res.F)\n",
    "print(\"Constraint violation: %s\" % res.CV)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
